import { constantRoutes, staticRoutes, staticHeadRoutes } from '@/router'
import { generateRoute } from '@/api/system/route'
import Layout from '@/layout'
import RouterView from '@/components/RouterView'
import IFrame from '@/components/IFrameView'

const state = {
  routes: [],
  addRoutes: [],
  sidebarRouters: [],
  navbarRouters: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_SIDEBAR_ROUTERS: (state, routes) => {
    state.sidebarRouters = routes
  },
  SET_NAVBAR_ROUTES: (state, routes) => {
    state.navbarRouters = routes
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    let rewriteRoutes = []
    let navbarRoutes = []
    return new Promise((resolve, reject) => {
      generateRoute().then(response => {
        const sdata = JSON.parse(JSON.stringify(response.param))
        const rdata = JSON.parse(JSON.stringify(response.param))
        rewriteRoutes = filterAsyncRoutes(rdata, roles, true)
        navbarRoutes = filterAsyncRoutes(sdata, roles)

        navbarRoutes = staticHeadRoutes.concat(navbarRoutes)
        rewriteRoutes = staticRoutes.concat(rewriteRoutes)
        // 自定义页面
        rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', rewriteRoutes)
        commit('SET_SIDEBAR_ROUTERS', rewriteRoutes)
        commit('SET_NAVBAR_ROUTES', navbarRoutes)
        resolve(rewriteRoutes)
      }).catch(error => {
        commit('SET_ROUTES', rewriteRoutes)
        commit('SET_SIDEBAR_ROUTERS', rewriteRoutes)
        commit('SET_NAVBAR_ROUTES', navbarRoutes)
        reject(error)
      })
    })
  },
  changeSidebarRoutes({ commit }, routes) {
    commit('SET_SIDEBAR_ROUTERS', routes)
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 * @param includeChild  whether include child routes
 */
export function filterAsyncRoutes(routes, roles, includeChild = false) {
  return routes.filter(route => {
    if (hasPermission(roles, route)) {
      try {
        route.name = route.meta.title
        if (route.children) { // 父节点
          if (route.component === 'Layout') {
            route.component = Layout
          } else if (route.component === 'ParentView') {
            route.component = RouterView
          }
        } else {
          if (route.component === 'IFrame') {
            route.component = IFrame
            if (route.meta.target === 'iframe') {
              route.query = { url: route.path }
              route.path = '/components/IFrame'
            }
          } else { // 根节点
            route.component = loadView(route.path)
          }
        }
      } catch (e) {
        return false
      }

      if (includeChild && route.children) {
        route.children = filterAsyncRoutes(route.children, roles, includeChild)
      }

      if (!route.children || route.children.length === 0) {
        delete route['children']
      }

      return true
    }

    return false
  })
}

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views${view}`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
